In [3]:
class Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = None
self.right = None
Implement a Binary Search Tree
In [91]:
class BinarySearchTree:
def __init__(self, value=None):
self.root = Node(value)
def insert(self, root, value):
if root == None:
return Node(value)
if value < root.value:
if root.left == None:
root.left = self.insert(root.left, value)
else:
self.insert(root.left, value)
else:
if root.right == None:
root.right = self.insert(root.right, value)
else:
self.insert(root.right, value)
def preorder(self, root=None):
"""Root, Left, Right"""
if root == None:
root = self.root
return
print(root.value)
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root=None):
"""Left, Root, Right"""
if root == None:
root = self.root
return
self.inorder(root.left)
print(root.value)
self.inorder(root.right)
def postorder(self, root=None):
"""Left, Right, Root"""
if root == None:
root = self.root
return
self.postorder(root.left)
self.postorder(root.right)
print(root.value)
def bfs(self, root=None):
if root == None:
root = self.root
queue = []
visited = set()
print(root.value)
visited.add(root)
queue.append(root)
while len(queue) != 0:
curr = queue.pop(0)
adjacent = [curr.left, curr.right]
for n in adjacent:
if n == None:
return
if n not in visited:
print(n.value)
visited.add(n)
queue.append(n)
In [92]:
b = BinarySearchTree(100)
b.insert(b.root, 10)
b.insert(b.root, 101)
b.insert(b.root, 9)
In [93]:
b.preorder(b.root)
In [94]:
b.inorder(b.root)
In [95]:
b.postorder(b.root)
In [96]:
b.bfs()
In [ ]: